package com.mllweb.blog.base;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.databind.util.BeanUtil;
import com.mllweb.blog.core.digest.Base64Utils;
import com.mllweb.blog.data.orm.BlogUser;
import com.mllweb.blog.web.dto.User;
import com.mllweb.blog.web.session.SessionKey;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.io.IOException;

/**
 * 控制器基类
 */
public class BaseController {

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;
    protected Cookie[] cookies;

    @ModelAttribute
    private void modelAttribute(HttpServletRequest request, HttpServletResponse response, Model model) {
        this.request = request;
        this.response = response;
        this.session = request.getSession(true);
        this.cookies = request.getCookies();
        User user= (User) this.session.getAttribute(SessionKey.USER.toString());
        model.addAttribute("user",user);
    }

    protected void errorStatus(HttpStatus httpStatus) {
        this.response.setStatus(httpStatus.value());
        String page = "error/" + httpStatus.value();
        try {
            this.request.getRequestDispatcher(page).forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected String redirect(String url) {
        return "redirect:" + url;
    }

}
